//
//  UIViewController+Additions.m
//  Learn
//
//  Created by zyl_macbookpro on 2024/4/1.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "UIViewController+Additions.h"
#import <objc/runtime.h>
@implementation UIViewController (Additions)

#pragma mark -自定义初始化方法
- (id)initWithClassName:(NSString *)aClassName;
{
    Class class =NSClassFromString(aClassName);
   
   if (!class) {
      class = NSClassFromString([NSString stringWithFormat:@"%@",aClassName]);
   }
    
    self = [[class alloc] init];
    
    return self;
}
#pragma mark -扩展属性
- (NSObject *)paraObject
{
    return objc_getAssociatedObject(self, @"paraObject");
}

- (void)setParaObject:(NSDictionary *)paraObject
{
    objc_setAssociatedObject(self, @"paraObject", paraObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)setBackButtonIsHidden:(BOOL)hidden
{
    if (hidden)
    {
        UIBarButtonItem *barButtonItem =[[UIBarButtonItem alloc] initWithCustomView:[UIButton new]];
        self.navigationItem.leftBarButtonItems =@[barButtonItem];
        return;
    }
    UIButton *button =[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35, 50)];
    UIImage *img = IMAGENAMED(@"ic_back");
    [button setImage:img forState:UIControlStateNormal];
    [button setImage:img forState:UIControlStateHighlighted];
    button.width = img.size.width+15;
    [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [button setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 15)];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItems =@[item];
}
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)renderNavBarWithBackgroundImage:(UIImage * __nullable)img
                       backgroundColor:(UIColor * __nullable)bgColor
                           shadowColor:(UIColor * __nullable)sColor
                      textAttributeDic:(NSDictionary * __nullable)textAttributeDic
                      enableScrollEdgeAppearance:(BOOL)enable{
    if (@available(iOS 15.0, *)) {

        UINavigationBarAppearance *barApp = [UINavigationBarAppearance new];

       if(bgColor == LTClearColor)
       {
          barApp.backgroundEffect = nil;
       }
        barApp.backgroundImage = img;
        barApp.backgroundColor = bgColor;
        barApp.shadowColor = sColor;
        barApp.titleTextAttributes = textAttributeDic;
        self.navigationController.navigationBar.scrollEdgeAppearance = enable?barApp:nil;
        self.navigationController.navigationBar.standardAppearance = barApp;

    } else {
       [self.navigationController.navigationBar setBackgroundImage:img forBarMetrics:UIBarMetricsDefault];
        if (sColor) {
            [self.navigationController.navigationBar setShadowImage:[UIImage imageWithColor:sColor]];
        }
        else{
            [self.navigationController.navigationBar setShadowImage:[UIImage new]];
        }
        
        [self.navigationController.navigationBar setTitleTextAttributes:textAttributeDic];
    }
}
-(void)popToViewControllerWithClassName:(NSString *)viewController animated:(BOOL)animated{
    if (self.navigationController){
        for (NSInteger i=self.navigationController.viewControllers.count-2;i>0;i--){
            UIViewController *aViewController =[self.navigationController.viewControllers objectAtIndex:i];
            
            if ([NSStringFromClass([aViewController class]) isEqualToString:viewController]){
                [self.navigationController popToViewController:aViewController animated:animated];
                return;
            }
        }
        
        [self.navigationController popToRootViewControllerAnimated:animated];
    }
    else if([self isKindOfClass:[UINavigationController class]]){
        UINavigationController *nav =self;
        for (NSInteger i=nav.viewControllers.count-2;i>0;i--){
            UIViewController *aViewController =[nav.viewControllers objectAtIndex:i];

            if ([NSStringFromClass([aViewController class]) isEqualToString:viewController]){
                [nav popToViewController:aViewController animated:animated];
                return;
            }
        }

        [nav popToRootViewControllerAnimated:YES];
    }
}

-(void)pushToViewControllerWithClassName:(NSString *)viewController animated:(BOOL)animated{
    if (self.navigationController){
        UIViewController *aVC =[[UIViewController alloc] initWithClassName:viewController];
        aVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:aVC animated:animated];
    }
    else if ([self isKindOfClass:[UINavigationController class]]){
        UIViewController *aVC =[[UIViewController alloc] initWithClassName:viewController];
        [((UINavigationController *)self) pushViewController:aVC animated:animated];
    }
    else{
        NSLog(@"无法指定跳转");
    }
}
+(UIViewController *)currentViewController{
   
   __block UIViewController *vc;
   
   if ([NSThread isMainThread]) {
      vc = [self getCurrentVC];
   }else{
      dispatch_sync(dispatch_get_main_queue(), ^{
         vc = [self getCurrentVC];
      });
   }
   
   return vc;
}

+(UIViewController *)getCurrentVC{
   
    if ([[self getCurrentPresentVC] isKindOfClass:[UINavigationController class]]){
        UINavigationController *nav = (UINavigationController *)[self getCurrentPresentVC];
        return nav.topViewController;
    }
    else if ([[self getCurrentPushVC] isKindOfClass:[UIViewController class]]&&
             [self getCurrentPushVC].navigationController)
    {
        return [self getCurrentPushVC];
    }
    else{
        UIWindow * window = LTApp.window;
        
        if ([window.rootViewController isKindOfClass:[UITabBarController class]]) {
            return ((UINavigationController *)((UITabBarController *)window.rootViewController).selectedViewController).topViewController;
        }
    }
    
    return nil;
}
+(UIViewController *)getCurrentPushVC{
   
    UIViewController * aVC =nil;
    UIWindow *targetWindow =nil;
    
    UIWindow * window =[UIApplication sharedApplication].keyWindow;
    
    NSInteger keyWindowIndex =0;
    NSArray *windows =[[UIApplication sharedApplication] windows];
    
    if (window.windowLevel !=UIWindowLevelNormal||
        ![NSStringFromClass([window class]) hasPrefix:@"UI"])
    {
       for (UIWindow *tmpWin in windows) {
          if ([tmpWin isKindOfClass:[UIWindow class]]) {
             if (tmpWin.windowLevel ==UIWindowLevelNormal&&
                 [NSStringFromClass([tmpWin class]) hasPrefix:@"UI"])
             {
                 keyWindowIndex = [windows indexOfObject:tmpWin];
                 break;
             }
          }
       }
    }
    
    if (keyWindowIndex!=0&&
        [[windows objectAtIndex:keyWindowIndex] isKindOfClass:[UIWindow class]]) {
        targetWindow =[windows objectAtIndex:keyWindowIndex];
    }
    
    if (!targetWindow) {
        targetWindow =window;
    }
    
    UIView *frontView =[[targetWindow subviews] objectAtIndex:0];
    id nextResponder =[frontView nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]])
        aVC =nextResponder;
    else
        aVC =targetWindow.rootViewController;
    
    if ([aVC isKindOfClass:[UITabBarController class]])
    {
        aVC =((UINavigationController *)((UITabBarController *)aVC).selectedViewController).topViewController;
    }
    else if (!aVC.navigationController&&
             [LTApp.window.rootViewController isKindOfClass:[UITabBarController class]]){
        aVC =((UINavigationController *)((UITabBarController *)LTApp.window.rootViewController).selectedViewController).topViewController;
    }
    
    return aVC;
}
+(UIViewController *)getCurrentPresentVC{
    UIViewController *topVC =[UIApplication sharedApplication].keyWindow.rootViewController;
    if (topVC.presentedViewController){
        topVC =topVC.presentedViewController;
    }
    return topVC;
}
@end
